package com.liangxy.news.database;

import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;

import com.liangxy.news.model.News;
import com.liangxy.news.model.UserFollowNews;

import java.util.List;

/**
 * DAO for user follow news
 */
@Dao
public interface UserFollowNewsDao {
    
    /**
     * Insert a follow relationship
     * @param userFollowNews The follow relationship to insert
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insert(UserFollowNews userFollowNews);
    
    /**
     * Delete a follow relationship
     * @param userFollowNews The follow relationship to delete
     */
    @Delete
    void delete(UserFollowNews userFollowNews);
    
    /**
     * Check if user follows a news
     * @param userId User ID
     * @param newsId News ID
     * @return Whether the user follows the news
     */
    @Query("SELECT COUNT(*) > 0 FROM user_follow_news WHERE user_id = :userId AND news_id = :newsId")
    boolean isFollowing(String userId, String newsId);
    
    /**
     * Get news followed by a user
     * @param userId User ID
     * @return LiveData list of followed news IDs
     */
    @Query("SELECT news_id FROM user_follow_news WHERE user_id = :userId ORDER BY followTime DESC")
    LiveData<List<String>> getFollowedNewsIds(String userId);
    
    /**
     * Get all news followed by a user
     * @param userId User ID
     * @return LiveData list of followed news
     */
    @Query("SELECT n.* FROM news n INNER JOIN user_follow_news u ON n.uniquekey = u.news_id WHERE u.user_id = :userId ORDER BY u.followTime DESC")
    LiveData<List<News>> getFollowedNews(String userId);
    
    /**
     * Get follow count for a news
     * @param newsId News ID
     * @return Number of users following the news
     */
    @Query("SELECT COUNT(*) FROM user_follow_news WHERE news_id = :newsId")
    LiveData<Integer> getFollowCount(String newsId);
    
    /**
     * Delete all follows for a user
     * @param userId User ID
     */
    @Query("DELETE FROM user_follow_news WHERE user_id = :userId")
    void deleteAllByUser(String userId);
    
    /**
     * Delete follow relationship
     * @param userId User ID
     * @param newsId News ID
     */
    @Query("DELETE FROM user_follow_news WHERE user_id = :userId AND news_id = :newsId")
    void deleteByUserAndNews(String userId, String newsId);
} 